package de.akabahn.ebd.control;

import static de.akabahn.ebd.control.auth.AccessEnum.ACTIVE;
import static de.akabahn.ebd.control.auth.AccessEnum.RESTRICTED;
import static de.akabahn.ebd.control.auth.AccessEnum.TECHNICIAN;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Iterator;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.WindowManager;
import de.akabahn.ebd.control.auth.AccessEnum;
import de.akabahn.ebd.control.data.DebugDataContainer;

public abstract class EBD_BaseActivity extends Activity {

	protected String bahnhof;
	protected String userName;
	protected AccessEnum role;
	protected SharedPreferences preferences;
	protected DebugDataContainer ddc;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread paramThread, Throwable exception) {
                StringWriter stackTrace = new StringWriter();
                exception.printStackTrace(new PrintWriter(stackTrace));

                StringBuilder errormessage = new StringBuilder(exception.getMessage());
            	while (exception.getCause() != null) {
            		exception = exception.getCause();
            		errormessage.append("\n\t\t- ").append(exception.getMessage());
            	}

                Intent loginIntent = new Intent(EBD_BaseActivity.this, EBD_LoginActivity.class);
                loginIntent.putExtra("de.akabahn.ebd.control.errormessage", errormessage.toString());
                loginIntent.putExtra("de.akabahn.ebd.control.stacktrace", stackTrace.toString());
                loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(loginIntent);
                System.exit(0);
            }
        });

		PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
		preferences = PreferenceManager.getDefaultSharedPreferences(this);
		ddc = DebugDataContainer.getInstance();

		userName = getIntent().getExtras().getString("de.akabahn.ebd.control.userName");
		role = AccessEnum.valueOf(getIntent().getExtras().getString("de.akabahn.ebd.control.roleName"));
		bahnhof = getIntent().getExtras().getString("de.akabahn.ebd.control.bhf");

		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.options_menu, menu);

		return role != RESTRICTED;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.findItem(R.id.menu_shuntmode).setVisible(false);
		menu.findItem(R.id.menu_speed_ctrl).setVisible(false);
		menu.findItem(R.id.menu_fst).setVisible(false);
		menu.findItem(R.id.menu_debugdata).setVisible(role == ACTIVE || role == TECHNICIAN);

		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.menu_debugdata:
				handleMenuDebugData();
				break;
			case R.id.menu_changepwd:
				Intent changePassword = new Intent(this, EBD_ChangePasswordActivity.class);
				changePassword.putExtra("de.akabahn.ebd.control.userName", userName);
				changePassword.putExtra("de.akabahn.ebd.control.roleName", role.name());
				startActivity(changePassword);
				break;
		}

		return role != RESTRICTED;
	}

	protected void handleException(Exception exception) {
        StringWriter stackTrace = new StringWriter();
        exception.printStackTrace(new PrintWriter(stackTrace));

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
		alertDialogBuilder.setTitle(getResources().getString(R.string.control_communicationError));
		alertDialogBuilder.setMessage(stackTrace.toString());
		alertDialogBuilder.setCancelable(false);
		alertDialogBuilder.setNeutralButton(getResources().getString(R.string.control_labelOK),
			new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});

		AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}

	protected void handleMenuDebugData() {
		StringBuilder buf = new StringBuilder();
		Iterator<String> iter = ddc.getQueue().iterator();
		while (iter.hasNext()) {
			buf.append(iter.next()).append("\n");
		}

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
		alertDialogBuilder.setTitle(getResources().getString(R.string.control_debugdata));
		alertDialogBuilder.setMessage(buf.toString());
		alertDialogBuilder.setCancelable(false);
		alertDialogBuilder.setPositiveButton(getResources().getString(R.string.control_labelOK),
			new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
		alertDialogBuilder.setNegativeButton(getResources().getString(R.string.control_labelDelete),
			new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					ddc.getQueue().clear();
					dialog.cancel();
				}
			});

		AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}
}
